<template>
  <div class="app-container">

    <StoreNav :title="title" right-text="购物车" @click-left="goBack" @click-right="handleManage"
      class="nav-bar--fixed " />
    <div class="product-section">
      <div class="content">
        <!-- 页面内容 -->
      </div>
    </div>
    <div class="product-container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <input v-model="searchQuery" type="text" placeholder="搜索商品" class="search-input" @input="filterProducts" />
        <button>
          <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M21 38C30.3888 38 38 30.3888 38 21C38 11.6112 30.3888 4 21 4C11.6112 4 4 11.6112 4 21C4 30.3888 11.6112 38 21 38Z"
              fill="#f3f0ff" stroke="#8a57f5" stroke-width="4" stroke-linejoin="round" />
            <path d="M26.657 14.3431C25.2093 12.8954 23.2093 12 21.0001 12C18.791 12 16.791 12.8954 15.3433 14.3431"
              stroke="#FFF" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
            <path d="M33.2216 33.2217L41.7069 41.707" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
              stroke-linejoin="round" />
          </svg>
        </button>
      </div>

      <!-- 商品筛选 -->
      <div class="filters">
        <div class="filter-scroll">
          <span v-for="filter in filters" :key="filter.id" class="filter-item"
            :class="{ active: activeFilter === filter.id }" @click="changeFilter(filter.id)">
            {{ filter.label }}
          </span>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <div v-for="(product, index) in filteredProducts" :key="index" class="product-item"
          @click="goToDetile(product.id)">
          <div class="product-image">
            <img :src="product.imageUrl" alt="商品图片" />
          </div>
          <div class="product-info">
            <h3 class="product-title">{{ product.name }}</h3>
            <p class="product-desc">{{ product.description }}</p>
            <p class="product-price">¥{{ product.price }}</p>
            <p class="product-stock">库存：{{ product.stock }}</p>
          </div>
          <button class="add-cart-btn" @click.stop="addToCart(product.id, $event)">
            <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M39 32H13L8 12H44L39 32Z" fill="#f3f0ff" />
              <path d="M3 6H6.5L8 12M8 12L13 32H39L44 12H8Z" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
                stroke-linejoin="round" />
              <circle cx="13" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
                stroke-linejoin="round" />
              <circle cx="39" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
                stroke-linejoin="round" />
            </svg>
          </button>
        </div>
        <div v-if="filteredProducts.length === 0" class="empty-tip">没有找到相关商品</div>
      </div>
    </div>
  </div>

  <div class="cart-block cart-icon" @click="handleCartClick" @touchstart="startDrag" @touchmove="onDrag"
    @touchend="endDrag" ref="cartButton">
    <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M39 32H13L8 12H44L39 32Z" fill="#f3f0ff" />
      <path d="M3 6H6.5L8 12M8 12L13 32H39L44 12H8Z" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
        stroke-linejoin="round" />
      <circle cx="13" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
      <circle cx="39" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
    </svg>
  </div>

  <!-- 登录确认弹窗 -->
  <div v-if="showLoginConfirm" class="login-confirm-overlay" @click="closeLoginConfirm">
    <div class="login-confirm-dialog" @click.stop>
      <div class="login-confirm-content">
        <div class="login-confirm-title">您当前未登录</div>
        <div class="login-confirm-text">登录后才能使用该功能</div>
        <div class="login-confirm-buttons">
          <button class="login-btn" @click="goToLogin">去登录</button>
          <button class="cancel-btn" @click="closeLoginConfirm">再看看</button>
        </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import StoreNav from '@/components/storeNav/StoreNav.vue'
import { getProductList, addProductToCart } from '@/views/productList/api/index'
import { useUserStore } from '@/stores/user';
import { showToast } from 'vant';
defineOptions({
  name: 'ProductList',
})

const userStore = useUserStore();
const route = useRoute()
const router = useRouter()
const title = ref('页面')
const showLoginConfirm = ref(false);
// 关闭登录确认弹窗
const closeLoginConfirm = () => {
  showLoginConfirm.value = false;
};

// 去登录
const goToLogin = () => {
  router.push({ path: "/login" });
  closeLoginConfirm();
};

const goBack = () => {
  router.go(-1)
}

const handleManage = () => {
  router.push({
    name: 'ShoppingCart',
  })
}

const goToDetile = (productId) => {
  router.push({
    name: 'ProductDetail',
    params: { id: productId }
  })
}
const showCart = () => {
  router.push({
    name: 'ShoppingCart',
    params: { id: 14 }//用户id--记得换
  })
}
// 筛选条件
const filters = ref([
  { id: 'all', label: '全部' },
  { id: 'hot', label: '热卖' },
  { id: 'new', label: '新品' },
  { id: 'discount', label: '价格' },
])

// 当前激活的筛选
const activeFilter = ref('all')
// 搜索关键词
const searchQuery = ref('')

// 商品数据
const products = ref([])

// 切换筛选条件
const changeFilter = (filterId) => {
  activeFilter.value = filterId
}

// 过滤后的商品列表
const filteredProducts = computed(() => {
  let result = [...products.value]

  //价格排序
  if (activeFilter.value === 'discount') {
    result.sort((a, b) => b.price - a.price)
  }
  // 热卖排序
  if (activeFilter.value === 'hot') {
    result.sort((a, b) => a.stock - b.stock)
  }
  // 新品排序
  if (activeFilter.value === 'new') {
    result.sort((a, b) => b.id - a.id)
  }

  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      (product) =>
        product.name.toLowerCase().includes(query) ||
        product.description.toLowerCase().includes(query),
    )
  }

  return result
})

// 搜索过滤（防抖可以在这里添加）
const filterProducts = () => {
  // 这里可以添加防抖逻辑
}

// 加入购物车
const addToCart = (productId, event) => {
  // 未登录提示登录  
  if (!userStore.token) {
    showToast('请先登录');
    return;
  }
  const productImage = event.currentTarget.closest('.product-item').querySelector('img')
  if (!productImage) return

  const cartIcon = document.querySelector('.cart-icon') // 购物车的目标位置
  if (!cartIcon) return

  const cloneImg = productImage.cloneNode(true) // 复制图片
  const imgRect = productImage.getBoundingClientRect()
  const cartRect = cartIcon.getBoundingClientRect()

  cloneImg.style.position = 'fixed'
  cloneImg.style.left = `${imgRect.left}px`
  cloneImg.style.top = `${imgRect.top}px`
  cloneImg.style.width = `${imgRect.width}px`
  cloneImg.style.height = `${imgRect.height}px`
  cloneImg.style.borderRadius = '50%'
  cloneImg.style.transition = 'all 0.8s ease-in-out'
  cloneImg.style.zIndex = '1000'
  document.body.appendChild(cloneImg)

  // 触发动画
  setTimeout(() => {
    cloneImg.style.left = `${cartRect.left + cartRect.width / 2}px`
    cloneImg.style.top = `${cartRect.top + cartRect.height / 2}px`
    cloneImg.style.width = '20px'
    cloneImg.style.height = '20px'
    cloneImg.style.opacity = '0'
  }, 10)

  // 动画完成后移除
  setTimeout(() => {
    document.body.removeChild(cloneImg)
  }, 800)

  console.log('加入购物车', productId)
  addProductToCart(userStore.userInfo.id, productId, 1)

}

// 拖拽相关变量
const isDragging = ref(false)
const initialX = ref(0)
const initialY = ref(0)
const currentX = ref(0)
const currentY = ref(0)
const cartButton = ref(null)

// 开始拖拽
const startDrag = (event) => {
  // 只有点击而不是拖拽时才导航到购物车
  isDragging.value = false

  // 记录初始触摸位置
  initialX.value = event.touches[0].clientX
  initialY.value = event.touches[0].clientY

  // 获取按钮当前位置
  const button = event.currentTarget
  button.classList.add('no-transition') // 禁用过渡效果以提高响应速度

  // 保存当前位置
  const buttonRect = button.getBoundingClientRect()
  currentX.value = buttonRect.left
  currentY.value = buttonRect.top
}

// 拖拽中
const onDrag = (event) => {
  // 如果移动超过一定距离，标记为拖拽而不是点击
  const touchX = event.touches[0].clientX
  const touchY = event.touches[0].clientY

  const deltaX = Math.abs(touchX - initialX.value)
  const deltaY = Math.abs(touchY - initialY.value)

  // 如果移动超过3px，认为是拖拽（降低阈值提高灵敏度）
  if (deltaX > 3 || deltaY > 3) {
    isDragging.value = true

    const button = event.currentTarget
    button.classList.add('dragging')

    // 直接使用触摸点位置计算，减少计算延迟
    const buttonWidth = button.offsetWidth
    const buttonHeight = button.offsetHeight

    // 计算新位置（手指位置减去按钮尺寸的一半，使按钮中心跟随手指）
    const newLeft = touchX - buttonWidth / 2
    const newTop = touchY - buttonHeight / 2

    // 限制在屏幕内
    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    const boundedLeft = Math.max(0, Math.min(newLeft, windowWidth - buttonWidth))
    const boundedTop = Math.max(0, Math.min(newTop, windowHeight - buttonHeight))

    // 更新按钮位置（使用transform而不是left/top属性，提高性能）
    button.style.transform = `translate3d(${boundedLeft}px, ${boundedTop}px, 0)`
    button.style.left = '0'
    button.style.top = '0'
    button.style.right = 'auto'
    button.style.bottom = 'auto'

    // 阻止默认行为和事件冒泡
    event.preventDefault()
    event.stopPropagation()
  }
}

// 结束拖拽并吸附
const endDrag = (event) => {
  const button = event.currentTarget
  button.classList.remove('no-transition') // 恢复过渡效果

  if (isDragging.value) {
    isDragging.value = false
    button.classList.remove('dragging')

    // 获取当前位置
    const buttonRect = button.getBoundingClientRect()
    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    // 重置transform
    button.style.transform = 'none'

    // 计算是否应该吸附到左侧或右侧
    const buttonCenterX = buttonRect.left + buttonRect.width / 2

    // 设置垂直位置（保持在当前高度，但不超出屏幕）
    const safeTop = Math.max(20, Math.min(buttonRect.top, windowHeight - buttonRect.height - 20))
    button.style.top = `${safeTop}px`
    button.style.bottom = 'auto'

    if (buttonCenterX < windowWidth / 2) {
      // 吸附到左侧
      button.style.left = '20px'
      button.style.right = 'auto'
    } else {
      // 吸附到右侧
      button.style.right = '20px'
      button.style.left = 'auto'
    }

    // 阻止点击事件
    event.stopPropagation()
    return false
  }
}

// 添加点击处理函数，只有在非拖拽状态下才导航
const handleCartClick = (event) => {
  if (!isDragging.value) {
    if (!userStore.token || !userStore.userInfo || !userStore.userInfo.id) {
      showLoginConfirm.value = true;
      return;
    }
    showCart();
  }
}

onMounted(async () => {
  title.value = route.params.name
  // 这里可以根据ID获取商品详情数据
  const res = await getProductList(route.params.id)
  if (res.data.code === 200) {
    products.value = res.data.data
  }
})
</script>

<style lang="scss" scoped>
// 变量定义
$text-color: #333;
$border-color: #eee;
$font-size-sm: 12px;
$font-size-md: 14px;
$font-size-lg: 16px;
$red-color: #f45f5f;
$purple-color: #845ef5;
$gray: #f3f0ff;

.app-container {
  display: block;
  width: 100%;
  overflow: hidden;
  background: #000;
  box-sizing: border-box;
}

.product-section {
  padding-top: 44px;
}

.product-container {
  background: #f3f0ff;
  min-height: 100vh;
  width: 100%;
  overflow: hidden;
}

// 搜索栏样式
.search-bar {
  background: $gray;
  padding: 10px 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .search-input {
    width: 90%;
    height: 36px;
    border-radius: 18px 0 0 18px;
    border: 1px solid $border-color;
    padding: 0 15px;
    font-size: $font-size-md;
  }

  button {
    width: 10%;
    height: 36px;
    text-align: center;
    border-radius: 0 18px 18px 0;
    border: none;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 筛选栏样式
.filters {
  overflow-x: auto;
  background: $gray;
  width: 100%;
  margin: 10px 0;

  .filter-scroll {
    display: flex;
    gap: 15px;
    padding: 0 5px;
    white-space: nowrap;
  }

  .filter-item {
    padding: 6px 12px;
    border-radius: 15px;
    background: #ffffff;
    color: $text-color;
    font-size: $font-size-sm;

    &.active {
      background: $purple-color;
      color: white;
    }
  }
}

// 商品列表样式
.product-list {
  width: 100%;

  .product-item {
    display: flex;
    gap: 12px;
    padding: 12px;
    margin-bottom: 10px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    position: relative;

    .product-image {
      flex: 0 0 100px;
      height: 100px;
      border-radius: 6px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 100%;
    }

    .product-title {
      font-size: $font-size-md;
      font-weight: bold;
      color: $text-color;
      width: 100%;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      margin-top: 10px;
    }

    .product-desc {
      font-size: $font-size-sm;
      color: #666;
      margin-bottom: 15px;
      line-height: 1.4;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      width: 50%;

    }

    .product-price {
      font-size: $font-size-lg;
      color: $red-color;
      margin: 0;
      font-weight: bold;
    }

    .product-stock {
      position: absolute;
      bottom: 15px;
      right: 70px;
      font-size: $font-size-sm;
      color: #666;
    }

    .add-cart-btn {
      position: absolute;
      top: 50%;
      right: 10px;
      background: #f8f6ff;
      border: none;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.nav-bar--fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}

.cart-block {
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #f5f2ff, #e7ddff);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 80px;
  right: 20px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 12px rgba(124, 77, 255, 0.25);
  color: #FFFFFF;
  font-size: 14px;
  font-weight: 500;
  z-index: 100;
  touch-action: none;
  /* 防止触摸事件被浏览器处理 */
  user-select: none;
  /* 防止文本选择 */
  will-change: transform;
  /* 提示浏览器优化变换性能 */

  &.no-transition {
    transition: none !important;
  }

  // 添加内部光晕效果
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at center, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 70%);
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px) scale(1.05);
    box-shadow: 0 6px 16px rgba(124, 77, 255, 0.35);

    &::before {
      opacity: 1;
    }
  }

  &:active {
    transform: translateY(-2px) scale(0.98);
    box-shadow: 0 3px 8px rgba(124, 77, 255, 0.2);
  }

  // 添加涟漪动画效果
  &::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: 2px solid #7C4DFF;
    animation: ripple 1.5s ease-out infinite;
    opacity: 0;
  }

  // 拖拽时的样式
  &.dragging {
    opacity: 0.9;
    box-shadow: 0 8px 20px rgba(124, 77, 255, 0.4);
    transform: scale(1.1);
    transition: box-shadow 0.2s ease, opacity 0.2s ease;
  }

  svg {
    pointer-events: none;
    /* 确保SVG不会干扰触摸事件 */
  }
}

@keyframes ripple {
  0% {
    transform: scale(1);
    opacity: 0.4;
  }

  100% {
    transform: scale(1.4);
    opacity: 0;
  }
}

.login-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.login-confirm-dialog {
  width: 80%;
  max-width: 300px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-confirm-content {
  padding: 20px;
}

.login-confirm-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
  color: #333;
}

.login-confirm-text {
  font-size: 14px;
  margin-bottom: 20px;
  text-align: center;
  color: #666;
}

.login-confirm-buttons {
  display: flex;
  justify-content: space-between;
}

.login-btn {
  flex: 1;
  margin-right: 10px;
  padding: 10px 0;
  background-color: #dbd2f1;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
}

.cancel-btn {
  flex: 1;
  padding: 10px 0;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}
</style>
